import dayjs from 'dayjs'
import {
  timeCardOrderDataByDay,
  timeCardOrderDataByMonth,
  chargingTimeDataByDay,
  chargingTimeDataByMonth,
  electricityStatisticByDay,
  electricityStatisticByMonth,
  plugNumChargingTimeStatistic,
} from '@/api/chargeStatistics'
import * as visualizationFun from '@/utils/visualizationFun'
import _ from 'lodash'

const defalutOptions = {
  xAxisType: 'day',
  setOption: () => {},
  keys: [],
  instance: null,
}

export const commonSettings = (options = defalutOptions, data) => {
  if (!Array.isArray(data)) return
  let socketXAxis = data.map((item) => {
    try {
      if (options.xAxisFormat) {
        return options.xAxisFormat(item)
      } else if (options.xAxisType == 'day') {
        return dayjs(item.day).format('YYYY.MM.DD')
      } else if (options.xAxisType == 'month') {
        let str = item.month.toString()
        if (str.length < 6) return '-'
        return str.slice(0, 4) + '.' + str.slice(4)
      }
      return '-'
    } catch (err) {
      console.log(err)
      return '-'
    }
  })

  let socketYAxis = [],
    socketDatas = [],
    socketMaxs = []

  options.keys.forEach((item) => {
    let yAxisItem = {
      name: item.yAxisName,
      show: true,
      isPercent: item.isPercent,
    }

    socketYAxis.push(yAxisItem)

    let socketData = data.map((data) => {
      if (item.isPercent) {
        let str = data[item.value].replace('%', '').replace(',', '')
        let number = parseInt(str)

        return number
      }
      return data[item.value]
    })

    socketDatas.push(socketData)
    let socketMax = visualizationFun.getMax(socketData)
    socketMaxs.push(socketMax)
  })

  if (options.setOption) {
    options.setOption(socketXAxis, socketYAxis, socketDatas, socketMaxs)
  } else {
    if (!options.instance) return

    let isHaveNegative = visualizationFun.getMin(_.concat(...socketDatas))

    let yAxis = socketYAxis.map((item, index) => {
      let max = Math.ceil(socketMaxs[index])
      let interval = max / 5

      let obj = {
        name: item.name,
        show: item.show,
        max,
        interval,
        min: () => {
          return isHaveNegative ? -max : 0
        },
      }

      if (index == 0) {
        obj.nameTextStyle = {
          padding: [0, 100, 0, 120],
        }
      }

      return obj
    })
    let series = socketDatas.map((item, index) => {
      return {
        name: options.keys[index].seriesName,
        data: item,
        yAxisIndex: index,
      }
    })

    let xAxis = {
      data: socketXAxis,
      show: true,
    }

    if (socketXAxis.length > 10) {
      xAxis.axisLabel = {
        rotate: 45,
      }
    } else {
      xAxis.axisLabel = {
        rotate: 0,
      }
    }

    options.instance.setOption({
      animation: true,
      xAxis,
      yAxis,
      series,
    })
  }
}

// 每日套餐订购数
export const handleDayTimecardTableData = (
  params,
  instance,
  completeCallback
) => {
  timeCardOrderDataByDay(params)
    .then((res) => {
      let dailyPackXAxis = []
      let timeCardSum = []
      let andEnergyCardSum = []
      res.forEach((item) => {
        dailyPackXAxis.push(dayjs(item.day).format('YYYY.MM.DD'))
        timeCardSum.push(item.timeCardCount)
        andEnergyCardSum.push(item.andEnergyCardCount)
      })
      let timeCardMax = visualizationFun.getMax(timeCardSum)
      let andEnergyMax = visualizationFun.getMax(andEnergyCardSum)
      let yAxisMax = visualizationFun.getMax([timeCardMax, andEnergyMax])

      instance.setOption({
        animation: true,
        xAxis: {
          data: dailyPackXAxis,
          show: true,
        },
        yAxis: [
          {
            name: '套餐订单数（个）',
            max: yAxisMax,
            show: true,
            nameTextStyle: {
              padding: [100, 0, 0, 100],
            },
            interval: yAxisMax / 5,
          },
        ],
        series: [
          {
            name: '时长卡订单数',
            data: timeCardSum,
          },
          {
            name: '和能量订单数',
            data: andEnergyCardSum,
          },
        ],
      })
    })
    .catch((err) => {
      console.log(err)
    })
    .finally(() => {
      completeCallback()
    })
}

// 每月套餐订购数
export const handleMonthTimecardTableData = (
  params,
  instance,
  completeCallback
) => {
  timeCardOrderDataByMonth(params)
    .then((res) => {
      let monthlyPackXAxis = []
      let timeCardSum = []
      let andEnergyCardSum = []
      let timeCardRate = []
      let andEnergyCardRate = []
      res.forEach((item) => {
        let XAxis = item.month.toString()
        XAxis =
          XAxis.length < 6 ? '-' : XAxis.slice(0, 4) + '.' + XAxis.slice(4)
        let rateOfIncrease = parseInt(
          item.rateOfIncrease.replace('%', '').replace(',', '')
        )
        let andEnergyRateOfIncrease = parseInt(
          item.andEnergyRateOfIncrease.replace('%', '').replace(',', '')
        )
        monthlyPackXAxis.push(XAxis)
        timeCardSum.push(item.timeCardCount)
        andEnergyCardSum.push(item.andEnergyCount)
        timeCardRate.push(rateOfIncrease)
        andEnergyCardRate.push(andEnergyRateOfIncrease)
      })
      let timeCardMax = visualizationFun.getMax(timeCardSum)
      let andEnergyMax = visualizationFun.getMax(andEnergyCardSum)
      let yAxisSumMax = visualizationFun.getMax([timeCardMax, andEnergyMax])
      let timeCardRateMax = visualizationFun.getMax(timeCardRate)
      let andEnergyRateMax = visualizationFun.getMax(andEnergyCardRate)
      let yAxisRateMax = visualizationFun.getMax([
        timeCardRateMax,
        andEnergyRateMax,
      ])
      let isHaveNegative = visualizationFun.getMin(
        _.concat(timeCardSum, andEnergyCardSum, timeCardRate, andEnergyCardRate)
      )
      instance.setOption({
        animation: true,
        xAxis: {
          data: monthlyPackXAxis,
          show: true,
        },
        yAxis: [
          {
            name: '套餐订单数（个）',
            show: true,
            max: yAxisSumMax,
            interval: yAxisSumMax / 5,
            min: function () {
              return isHaveNegative ? -yAxisSumMax : 0
            },
          },
          {
            name: '增长率(%)',
            show: true,
            max: yAxisRateMax,
            interval: yAxisRateMax / 5,
            min: function () {
              return isHaveNegative ? -yAxisRateMax : 0
            },
          },
        ],
        series: [
          {
            name: '时长卡订单数',
            data: timeCardSum,
            yAxisIndex: 0,
          },
          {
            name: '和能量订单数',
            data: andEnergyCardSum,
            yAxisIndex: 0,
          },
          {
            name: '时长卡增长率',
            data: timeCardRate,
            yAxisIndex: 1,
          },
          {
            name: '和能量增长率',
            data: andEnergyCardRate,
            yAxisIndex: 1,
          },
        ],
      })
    })
    .catch((err) => {
      console.log(err)
    })
    .finally(() => {
      completeCallback()
    })
}

// 每日充电时长走势图
export const handleDayChargeTimeTableData = (
  params,
  instance,
  completeCallback
) => {
  chargingTimeDataByDay(params)
    .then((res) => {
      commonSettings(
        {
          xAxisType: 'day',
          instance,
          keys: [
            {
              value: 'chargingDurationCount',
              yAxisName: '充电时长(分)',
              seriesName: '充电时长',
            },
          ],
        },
        res
      )
    })
    .catch((err) => {
      console.log(err)
    })
    .finally(() => {
      completeCallback()
    })
}

// 每月充电时长走势图
export const handleMonthChargeTimeTableData = (
  params,
  instance,
  completeCallback
) => {
  chargingTimeDataByMonth(params)
    .then((res) => {
      commonSettings(
        {
          xAxisType: 'month',
          instance,
          keys: [
            {
              value: 'chargingDurationCount',
              yAxisName: '充电时长(分)',
              seriesName: '充电时长',
            },
            {
              value: 'rateOfIncrease',
              yAxisName: '增长率(%)',
              seriesName: '增长率(%)',
              isPercent: true,
            },
          ],
        },
        res
      )
    })
    .catch((err) => {
      console.log(err)
    })
    .finally(() => {
      completeCallback()
    })
}

// 每日充电量走势图
export const handleDayElectricityStatisticTableData = (
  params,
  instance,
  completeCallback
) => {
  electricityStatisticByDay(params)
    .then((res) => {
      commonSettings(
        {
          xAxisType: 'day',
          instance,
          keys: [
            {
              value: 'electricityCount',
              yAxisName: '充电量(度)',
              seriesName: '充电量',
            },
          ],
        },
        res
      )
    })
    .catch((err) => {
      console.log(err)
    })
    .finally(() => {
      completeCallback()
    })
}

export const handleMonthElectricityStatisticTableData = (
  params,
  instance,
  completeCallback
) => {
  electricityStatisticByMonth(params)
    .then((res) => {
      commonSettings(
        {
          xAxisType: 'month',
          instance,
          keys: [
            {
              value: 'electricityCount',
              yAxisName: '充电量(度)',
              seriesName: '充电量',
            },
            {
              value: 'rateOfIncrease',
              yAxisName: '增长率(%)',
              seriesName: '增长率(%)',
              isPercent: true,
            },
          ],
        },
        res
      )
    })
    .catch((err) => {
      console.log(err)
    })
    .finally(() => {
      completeCallback()
    })
}

export const handleProvinceData = (params, instance, callback) => {
  plugNumChargingTimeStatistic(params)
    .then((res) => {
      commonSettings(
        {
          xAxisType: 'day',
          instance,
          keys: [
            {
              value: 'plugNumChargingTimeCount',
              yAxisName: '充电时长(分)',
              seriesName: '充电时长',
            },
            {
              value: 'plugNumChargingAvgTime',
              yAxisName: '端口平均充电时长',
              seriesName: '端口平均充电时长',
            },
          ],
          xAxisFormat: (item) => {
            return item.provinceName
          },
        },
        res
      )
    })
    .catch((err) => {
      console.log(err)
    })
    .finally(() => {
      callback()
    })
}
